<template>
  <div class="search">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      left-arrow
      title="搜索中心"
      @click-left="$router.back()"
      fixed
      placeholder
    />
    <!-- 搜索框 -->
    <van-search
      show-action
      placeholder="请输入搜索关键词"
      shape="round"
      v-model.trim="keyword"
      @search="onSearch"
      @input="onInput"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>

    <!-- 推荐词 -->
    <van-cell-group>
      <van-cell
        icon="search"
        v-for="(item, index) in showList"
        :key="index"
        @click="
          $router.push({ path: '/searchResult', query: { q: list[index] } })
        "
      >
        <template #title>
          <div v-html="item"></div>
        </template>
      </van-cell>
    </van-cell-group>

    <!-- 搜索历史 -->
    <van-cell-group>
      <van-cell title="历史记录"> </van-cell>
      <van-cell title="单元格">
        <van-icon name="close" />
      </van-cell>
      <van-cell title="单元格">
        <van-icon name="close" />
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { getSuggestionList } from './home'
export default {
  name: 'search',
  data () {
    return {
      keyword: '',
      list: [],
      timeId: null
    }
  },
  methods: {
    onSearch () {
      // 跳转搜索页
      this.$router.push({ path: '/searchResult', query: { q: this.value } })
    },
    onInput () {
      clearTimeout(this.timeId)
      this.timeId = setTimeout(async () => {
        if (this.keyword.length == 0) {
          this.list = []
          return
        }
        let res = await getSuggestionList(this.keyword)
        // console.log(res)
        this.list = res.data.data.options
      }, 500)
    }
  },
  computed: {
    showList () {
      return this.list.map(item => {
        let regExp = new RegExp(this.keyword, 'ig')
        return item.replace(regExp, match => {
          return `<span style='color:red'>${match}</span>`
        })
      })
    }
  }
}
</script>

<style></style>
